package com.sakura.socket.task;

import com.sakura.entity.Elderly;
import com.sakura.entity.HelpRequest;
import com.sakura.service.ElderlyService;
import com.sakura.service.HelpRequestService;
import com.sakura.socket.controller.WebSocketServer;
import com.sakura.util.EntityConverter;
import com.sakura.vo.HelpRequestDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.websocket.EncodeException;
import javax.websocket.Session;
import java.io.IOException;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.Map;

@Component
public class WebSocketTask {
    @Autowired
    private WebSocketServer webSocketServer;

    @Autowired
    private HelpRequestService helpRequestService;

    @Autowired
    private ElderlyService elderlyService;

    /**
     * 通过WebSocket每隔5秒向客户端发送消息
     */
    @Scheduled(cron = "0/5 * * * * ?")
    public void sendMessageToClient() throws EncodeException, IOException {
//        webSocketServer.sendToAllClient("这是来自服务端的消息："
//                + DateTimeFormatter.ofPattern("HH:mm:ss").format(LocalDateTime.now()));
//        Long id = 33l;
//        HelpRequest helpRequest = helpRequestService.getById(id);
//        Map<String, Object> message = new HashMap<>();
//        message.put("time", LocalTime.now());
//        message.put("id", id);
//        HelpRequestDTO helpRequestDTO = EntityConverter.copyAndGetSingle(helpRequest, HelpRequestDTO.class);
//        Elderly elderly = elderlyService.getById(helpRequest.getElderlyId());
//        helpRequestDTO.setElderlyName(elderly.getName());
//        helpRequestDTO.setElderlyPhone(elderly.getPhone());
//        message.put("event", helpRequestDTO);
//        //webSocketServer.sendObject("上线了");
//        Session myGridSession = webSocketServer.getMyGridSession(helpRequest.getGridId()+"");
//        myGridSession.getBasicRemote().sendObject(message);
//        webSocketServer.sendMyGrid(2l, 1l);

    }
}
